package com.ruoyi.foodworks.controller;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.foodworks.domain.CommentReply;
import com.ruoyi.foodworks.domain.CommentStats;
import com.ruoyi.foodworks.domain.ReplyRequest;
import com.ruoyi.foodworks.service.CommentReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 评论回复Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/foodworks/comments")
public class CommentReplyController extends BaseController {
    
    @Autowired
    private CommentReplyService replyService;
    
    /**
     * 获取评论回复列表
     */
    @GetMapping("/replies")
    public AjaxResult getReplies(@RequestParam Long commentId) {
        
        List<CommentReply> replies = replyService.getRepliesByCommentId(commentId);
        return AjaxResult.success(replies);
    }
    
    /**
     * 发送回复
     */
    @Log(title = "发送回复", businessType = BusinessType.INSERT)
    @PostMapping("/replies")
    public AjaxResult sendReply(@RequestBody ReplyRequest request) {
        CommentReply reply = replyService.createReply(request);
        return AjaxResult.success(reply);
    }
    
    /**
     * 删除回复
     */
    @Log(title = "删除回复", businessType = BusinessType.DELETE)
    @DeleteMapping("/replies/{replyId}")
    public AjaxResult deleteReply(@PathVariable Long replyId) {
        // 从token中获取用户ID
        Long userId = getUserId();
        boolean success = replyService.deleteReply(replyId, userId);
        
        if (success) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败或权限不足");
        }
    }
    
    /**
     * 获取回复详情
     */
    @GetMapping("/replies/{replyId}")
    public AjaxResult getReplyDetail(@PathVariable Long replyId) {
        CommentReply reply = replyService.getReplyDetail(replyId);
        return AjaxResult.success(reply);
    }
    
    /**
     * 获取评论统计信息
     */
    @GetMapping("/stats")
    public AjaxResult getCommentStats(@RequestParam List<Long> commentIds) {
        Map<Long, CommentStats> statsMap = replyService.getCommentStats(commentIds);
        return AjaxResult.success(statsMap);
    }
    
    /**
     * 获取单个评论的回复数量
     */
    @GetMapping("/stats/{commentId}")
    public AjaxResult getCommentReplyCount(@PathVariable Long commentId) {
        Integer replyCount = replyService.getReplyCountByCommentId(commentId);
        return AjaxResult.success(replyCount);
    }
}
